package servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * ServletConfig 类详解  ---- 记得看桌面上画的图 -- 画图解释
 *
 * 每个 Servlet 有自己独立的 Config 对象 看配置文件就知道了
 *
 */
public class ServletConfigDemo extends HttpServlet {

    public void service(HttpServletRequest req, HttpServletResponse res){
        // 获取 ServletConfig 配置信息对象
        ServletConfig servletConfig = getServletConfig();
        // 可以通过这个对象获取初始化的 配置信息
        String keyA = servletConfig.getInitParameter("keyA");
        System.out.println(keyA + " ");

        // 获取所有的初始参数名字
            // 迭代器写法
        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
        while(initParameterNames.hasMoreElements()){
            String key = initParameterNames.nextElement();
            String value = servletConfig.getInitParameter(key);
            System.out.println(key + " : " + value);
        }

        System.out.println("----------ServletContext获取参数---------");
        ServletContext servletContext = servletConfig.getServletContext();
        String encoding = servletContext.getInitParameter("encoding");
        System.out.println(encoding);

        // 这里向域对象中添加属性
        servletContext.setAttribute("keyA", "值");
        // 另外一个地方拿

        // 打印所有配置
        Enumeration<String> parameterNames = servletContext.getInitParameterNames();
        while(parameterNames.hasMoreElements()){
            String key = parameterNames.nextElement();
            System.out.println(key + " : " + servletContext.getInitParameter(key));
        }
    }
}